package com.sgb.kjwl.view.ui.activity.manage;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.luck.picture.lib.entity.LocalMedia;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityWebsiteReleaseBinding;
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent;
import com.sgb.kjwl.di.manage.EnterpriseManageModule;
import com.sgb.link.utils.SizeUtils;
import com.sgb.kjwl.view.ui.adapter.manage.WebsiteReleaseListAdapter;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.kjwl.viewmodel.manage.WebsiteReleaseModule;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * @author 张驰
 * @date 2021/5/10 14:32
 * @Description 企业网店—个人中心—宣传相册
 * @name com.sgb.kjwl.view.ui.activity.manage
 */
public class WebsiteReleaseActivity extends AppActivity {

    @Inject
    WebsiteReleaseModule viewModel;

    public static final int QIYEXIANGCE = 0; //宣传相册
    public static final int QIYEXINXI = 1; //信息简介
    public static final int QIYEZIZHI = 2; //专项资质
    public static final int YEJIZHENGMING = 3; //经营业绩
    public static final int QIYEDONGTAI = 4; //经营动态
    public static final int ZHISHICHANQUAN = 5; //知识产权
    public static final int HANGYERONGYU = 6; //荣誉荣耀
    private ActivityWebsiteReleaseBinding binding;

    private String titleName; // 当前进入模块标题
    private int MODELTYPE = 0; //当前进入模块标识
    private int siteType = 1; //网站类型  0-个人 1-企业 2-团队 默认为1
    private WebsiteReleaseListAdapter websiteReleaseListAdapter;
    boolean isLoadMore = false; // 是否是加载更多
    private String typesOfPropertyRights; // 产权类型

    private String[] typesOfProperty = new String[]{"商标", "专利", "版权"};// 产权类型

    private String[] mShowType = new String[]{"图片", "视频"};//宣传相册

    private boolean isEnableLoadMore = false; //是否可以上拉加载

    /**
     * 企业网店
     * 调用此方法是从我的界面跳转时，根据当前用户切换的身份来获取 网站类型类型
     * @param context
     * @param ModelType 网店模块
     */
    public static void start(Context context, int ModelType) {
        Intent intent = new Intent(context, WebsiteReleaseActivity.class);
        intent.putExtra("ModelType", ModelType);
//        intent.putExtra("siteNo",siteNo);
          //网站类型  0-个人 1-企业 2-团队 默认为1
        int siteType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1);
        intent.putExtra("siteType", siteType);
        context.startActivity(intent);
    }


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent).
                enterpriseManageModule(new EnterpriseManageModule(this)).
                build().inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(WebsiteReleaseActivity.this, R.layout.activity_website_release);
        binding.setViewModel(viewModel);
        getInItData();
        if (MODELTYPE == QIYEXIANGCE) { // 企业相册
            binding.include.rightView.setText("上传");
            binding.tablayout.setVisibility(View.VISIBLE);
            initShowTabLayout();
        } else {
            binding.include.rightView.setText("发布");
            binding.tablayout.setVisibility(View.GONE);
        }

        binding.include.rightView.setOnClickListener(this);
        binding.include.ivBack.setOnClickListener(this);
        binding.include.titleView.setText(titleName);
        if (MODELTYPE != QIYEXINXI) { // 信息简介 不需要使用列表模式承载
            initRecyclerView();
        }
    }

    /**
     * 初始化界面列表展示控件
     */
    private void initRecyclerView() {
        // SwipeRefreshLayout 刷新
        binding.listRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = true;
                viewModel.initData(isLoadMore);
                binding.listRefreshLayout.finishLoadMore(500);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = false;
                viewModel.initData(isLoadMore);
                binding.listRefreshLayout.finishRefresh(500);
            }
        });
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        binding.listRefreshLayout.setScrollBoundaryDecider(new ScrollBoundaryDecider() {
            @Override
            public boolean canRefresh(View content) {
                if (binding.myRecyclerView == null) return false;
                if (binding.myRecyclerView.computeVerticalScrollOffset() == 0)
                    return true;
                return false;
            }

            @Override
            public boolean canLoadMore(View content) {
                if (binding.myRecyclerView == null) return false;
                //获取recyclerView的高度
                binding.myRecyclerView.getHeight();
                //整个View控件的高度
                int scrollRange = binding.myRecyclerView.computeVerticalScrollRange();
                //当前屏幕之前滑过的距离
                int scrollOffset = binding.myRecyclerView.computeVerticalScrollOffset();
                //当前屏幕显示的区域高度
                int scrollExtent = binding.myRecyclerView.computeVerticalScrollExtent();
                int height = binding.myRecyclerView.getHeight();
                if (height > scrollRange) {
                    return false;
                }
                if (isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent) {
                    return true;
                }
                return false;
            }
        });
        // RecyclerView 和 Adapter 关联
        websiteReleaseListAdapter.bindToRecyclerView(binding.myRecyclerView);
        viewModel.getListMutableLiveData().observe(this, new Observer<List<Object>>() {
            @Override
            public void onChanged(List<Object> objectList) {
                isEnableLoadMore = objectList.size() >= 10;
                if (isLoadMore) {
                    websiteReleaseListAdapter.addData(objectList);
                } else {
                    websiteReleaseListAdapter.setNewData(objectList);
                }
            }
        });
    }

    /**
     * 初始化界面布局显示样式
     */
    private void getInItData() {
        websiteReleaseListAdapter = new WebsiteReleaseListAdapter(viewModel, new ArrayList<>());
        websiteReleaseListAdapter.setOnClickListener(new WebsiteReleaseListAdapter.OnClickListener() {
            @Override
            public void onDel(String id) {
                if (!ClickUtils.isDoubleClick()) {
                    showDialog(id);
                }
            }

            @Override
            public void onEditor(String id, String name) {
                if (!ClickUtils.isDoubleClick()) {
                    viewModel.onEditor(getActivity(), id, name);
                }
            }

            @Override
            public void onRoomClick(String id, String name) {
                if (!ClickUtils.isDoubleClick()) {
                    viewModel.onRoomClick(getActivity(), id, name);
                }
            }
        });
        View empty = LayoutInflater.from(this).inflate(R.layout.layout_null_list_change, binding.myRecyclerView, false);
        empty.setVisibility(View.VISIBLE);
        websiteReleaseListAdapter.setEmptyView(empty);
        MODELTYPE = getIntent().getIntExtra("ModelType", 0);
        siteType = getIntent().getIntExtra("siteType", 1);
        viewModel.setModeltype(MODELTYPE);
        String companyNo = "";
        if (siteType == 0){
            companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        } else {
            companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        }
        viewModel.setSiteNo(companyNo); //网店编号
        viewModel.setSiteType(siteType);
        switch (MODELTYPE) {
            case QIYEXIANGCE:
                titleName = "宣传展示";
                GridLayoutManager manager = new GridLayoutManager(getActivity(), 2);
                websiteReleaseListAdapter.setManager(manager, Glide.with(this));
                binding.myRecyclerView.setLayoutManager(manager);
                break;
            case QIYEXINXI:
                titleName = "信息简介";
                break;
            case QIYEZIZHI:
                titleName = "专项资质";
                break;
            case YEJIZHENGMING:
                titleName = "经营业绩";
                break;
            case QIYEDONGTAI:
                titleName = "经营动态";
                break;
            case ZHISHICHANQUAN:
                titleName = "知识产权";
                binding.include.titleView.setVisibility(View.GONE);
                initTabLayout();
                break;
            case HANGYERONGYU:
                titleName = "荣誉荣耀";
                break;
        }
    }

    //宣传相册二级
    private void initShowTabLayout() {
        for (String title : mShowType) {
            TabLayout.Tab tab = binding.tablayout.newTab();
            tab.setText(title);
            binding.tablayout.addTab(tab);
        }
        viewModel.setUploadType("" + 1);//固定为图片
        binding.tablayout.setTabMode(TabLayout.MODE_FIXED);
        //监听tabLayout1变化，根据变化相应刷新tabLayout2的内容
        binding.tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition() + 1;// 目前固定为图片
                viewModel.setUploadType("" + position);
                viewModel.initData(false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }


    /**
     * 初始化头部Tab控件 目前知识产权使用
     */
    private void initTabLayout() {
        binding.include.titleTabView.setVisibility(View.VISIBLE);
        binding.include.titleTabView.setSelectedTabIndicatorColor(getResources().getColor(R.color.white));
        binding.include.titleTabView.setSelectedTabIndicatorHeight(SizeUtils.dp2px(2));
        typesOfPropertyRights = typesOfProperty[0];
        viewModel.setTypesOfPropertyRights(typesOfPropertyRights); // 目前固定为企业
        for (String title : typesOfProperty) {
            TabLayout.Tab tab = binding.include.titleTabView.newTab();
            tab.setText(title);
            binding.include.titleTabView.addTab(tab);
        }
        binding.include.titleTabView.setTabMode(TabLayout.MODE_FIXED);
        //监听tabLayout1变化，根据变化相应刷新tabLayout2的内容
        binding.include.titleTabView.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                typesOfPropertyRights = typesOfProperty[position];
                viewModel.setTypesOfPropertyRights(typesOfPropertyRights); // 目前固定为企业
                viewModel.initData(false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        isLoadMore = false;
        viewModel.initData(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.right_view:
                if (!ClickUtils.isDoubleClick()) {
                    onClickRightView();
                }
                break;
        }
    }

    /**
     * 处理 发布按钮的点击事件
     */
    private void onClickRightView() {
        switch (MODELTYPE) {
            case QIYEXIANGCE: //宣传相册
                UploadPicAndVideoActivity.start(this,siteType);
                break;
//            case QIYEXINXI: //信息简介
//                MToast.showToast(this,"信息简介 发布");
//                break;
            case QIYEZIZHI: //专项资质
                WebsiteUpDataZhuanXiangZiZhiActivity.start(this, "资质", "",siteType);
                break;
            case YEJIZHENGMING: //经营业绩
                WebsiteUpDataJingYingYeJiActivity.start(this, "",siteType);
                break;
            case QIYEDONGTAI: //经营动态
                WebsiteUpDataJYDTActivity.start(this, "经营", "",siteType);
                break;
            case ZHISHICHANQUAN: //知识产权
                WebsiteUpDataZhiShiChanQuanActivity.start(this, typesOfPropertyRights, "",siteType);
                break;
            case HANGYERONGYU: //荣誉荣耀
                WebsiteUpDataRongYuRongYaoActivity.start(this, "荣誉", "", siteType);
                break;
            default:
                break;
        }
    }


    // 图片结果回调
    @Override
    protected void onPictureSelectorResult(List<LocalMedia> selectList) {
        // 获取到图片的本地路径
        String path = selectList.get(0).getCompressPath();
        //保存在文件中
        if (!TextUtils.isEmpty(path)) {
            File file = new File(path);
            //接口上传文件
            viewModel.uploadAvatar(getActivity(), file,siteType);
            //上传时，出现上传弹窗
            DialogHelper.showProgressDialog(this, null, "头像上传中...", 0, false, null).setCanceledOnTouchOutside(false);
        } else {
            MToast.showToast(getApplicationContext(), "获取图片失败！");
        }
    }

    private void showDialog(String id) {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失

        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_logout_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        tv_title.setVisibility(View.VISIBLE);
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);
        tv_title.setText("温馨提示");
        tv_message.setText("是否确认删除?");

        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.onDel(getActivity(), id);
                roundCornerDialog.dismiss();
            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }
}
